<template>
  <el-form :model="form" class="form-container" ref="formRef" :rules="formRules.rules" label-width="121px" :style="rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
    ? 'display:none'
    : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
      ? 'display:none'
      : ''
    ">
    <el-form-item label="新签/续签" prop="signType">
      <el-select v-model="form.signType" class="selectStyle" placeholder="请选择" @change="signTypeChange">
        <el-option v-for="item in signTypeOptionsArr" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="竞租方式" prop="competitionLeaseType">
      <el-select v-model="form.competitionLeaseType" class="selectStyle" placeholder="请选择" @change="competeTypeChange">
        <el-option v-for="item in competeTypeOptionsArr" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="承租方(乙方)" prop="haveCustomerValFlag">
      <el-input class="inputStyle" v-model="form.haveCustomerValFlag" placeholder="点击选择" readonly
        @click="showTenantryDialog('leaseCustomers')" />
    </el-form-item>


    <!-- 选择的租赁方客户 -->
    <div class="housesListBox" v-if="form.leaseCustomers.length">
      <el-form-item class="housesItemStyle" v-for="(n, i) in form.leaseCustomers" :key="i" :label="`乙方${i + 1}`">
        <img class="deletBtn" src="@/assets/iconImg/delet.png" alt="" @click="doDeleteLeaseCustomersList(i)" />
        <el-input v-model="n.customerName" placeholder="客户姓名" disabled />
      </el-form-item>
    </div>

    <el-form-item label="租赁的资产" prop="haveAssetValFlag">
      <el-input class="inputStyle" v-model="form.haveAssetValFlag" placeholder="点击选择" readonly @click="() => {
        showAssetDialog();
        selectedDom('assetsList');
      }
        " />
    </el-form-item>
    <!-- 选择的资产列表 -->
    <div class="housesListBox" v-if="form.assetsList.length">
      <el-form-item class="housesItemStyle" v-for="(n, i) in form.assetsList" :key="i" :label="`资产${i + 1}`">
        <img class="deletBtn" src="@/assets/iconImg/delet.png" alt="" @click="doDeletAssetsList(i)" />
        <el-input v-model="n.assetsName" placeholder="资产名称" disabled />
      </el-form-item>
    </div>



    <el-form-item label="租赁的房源" prop="haveHousingValFlag">
      <el-input class="inputStyle" v-model="form.haveHousingValFlag"
        :placeholder="!form.assetsList || !form.assetsList.length ? '请先选择租赁的资产' : '点击选择'" readonly
        :disabled="!form.assetsList || !form.assetsList.length" @click="() => {
          showHousingDialog();
          selectedDom('leaseHousings');
        }
          " />
    </el-form-item>
    <!-- 选择的房源列表 -->
    <div class="housesListBox" v-if="form.leaseHousings.length">
      <el-form-item class="housesItemStyle" v-for="(n, i) in form.leaseHousings" :key="i" :label="`房源${i + 1}`">
        <img class="deletBtn" src="@/assets/iconImg/delet.png" alt="" @click="doDeletHousesList(i)" />
        <el-input v-model="n.housingNumber" placeholder="门牌号" disabled />
        <el-input v-model="n.leaseArea" placeholder="租赁面积(平方米)" disabled />
      </el-form-item>
    </div>
    <el-form-item label="租赁总面积">
      <el-input v-model="form.leaseTotalArea" placeholder="点击选择" disabled />
    </el-form-item>

    <el-form-item class="limitInput" label="租赁期限" prop="sign_time">
      <el-date-picker v-model="form.sign_time" type="daterange" class="dateInputBox dateRangeBox"
        value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
        @change="onSignTimeChange" size="large" />
      <el-input v-model="form.yearCount" class="inputStyle" style="width: 45px" disabled placeholder="年" />
    </el-form-item>

    <el-form-item label="实际租金单价" prop="areaUnitPrice">
      <el-input v-model="form.areaUnitPrice" class="inputStyle" placeholder="请输入金额" clearable
        @click="selectedDom('areaUnitPrice')"
        @input="form.areaUnitPrice = limitInputNum(form.areaUnitPrice, 9, 2, true)" />
    </el-form-item>


    <el-form-item label="驿站交付天数" prop="giveDay">
      <el-input v-model="form.giveDay" class="inputStyle" placeholder="天数（单位：天）" clearable
        @click="selectedDom('giveDay')" @input="form.giveDay = limitInputNum(form.giveDay, 10, 0, false)">
        <template #append>天</template>
      </el-input>
    </el-form-item>

    <el-form-item label="使用目的" prop="purpose">
      <el-input v-model="form.purpose" class="inputStyle" maxlength="32" @click="selectedDom('businessPurpose')"
        placeholder="请输入使用目的" clearable />
    </el-form-item>

    <el-form-item label="经营用途" prop="businessPurpose">
      <el-input v-model="form.businessPurpose" class="inputStyle" maxlength="32" @click="selectedDom('businessPurpose')"
        placeholder="请输入经营用途" clearable />
    </el-form-item>
    <el-form-item label="租赁保证金" prop="deposit">
      <el-input v-model="form.deposit" class="inputStyle" placeholder="请输入租赁保证金金额（单位：元）"
        @input="form.deposit = limitInputNum(form.deposit, 9, 2, true)" @click="selectedDom('deposit')" />
    </el-form-item>
    <el-form-item class="limitInput" label="保证金缴纳时间">
      <el-date-picker v-model="form.depositPayTime" class="dateInputBox" value-format="YYYY-MM-DD" type="date"
        placeholder="请选择租赁保证金缴纳日期" size="large" @click="selectedDom('depositPayTime')">
      </el-date-picker>
    </el-form-item>
    <el-form-item class="limitInput" label="约定开业日期" prop="openTime">
      <el-date-picker v-model="form.openTime" class="dateInputBox" value-format="YYYY-MM-DD" type="date"
        placeholder="请选择开业日期" :disabled-date="openDisabledDate" size="large" @click="selectedDom('openTime')">
      </el-date-picker>
    </el-form-item>

    <el-form-item label="递增模式和比例">
      <el-radio-group v-model="form.increaseMode" @change="growChange">

        <el-radio :label="1">第
          <el-input :disabled="form.increaseMode != 1" style="width:70px;" v-model="form.increaseStartYear1"
            class="inputStyle" placeholder="N" @click="selectedDom('increaseStartYear1')" @input="
              form.increaseStartYear1 = limitInputNum(form.increaseStartYear1, 3, 0, false)
              " />
          年后，逐年递增
          <el-input :disabled="form.increaseMode != 1" style="width:70px;" v-model="form.increaseRate1"
            class="inputStyle" placeholder="%" @click="selectedDom('increaseRate1')"
            @input="form.increaseRate1 = limitInputNum(form.increaseRate1, 3, 0, false)" />%
        </el-radio>

        <el-radio :label="2">第
          <el-input :disabled="form.increaseMode != 2" style="width:70px;" v-model="form.increaseStartYear2"
            class="inputStyle" placeholder="N" @click="selectedDom('increaseStartYear2')" @input="
              form.increaseStartYear2 = limitInputNum(form.increaseStartYear2, 3, 0, false)
              " />
          年后，每隔<el-input :disabled="form.increaseMode != 2" style="width:70px;" v-model="form.periodicIncreaseInterval"
            class="inputStyle" placeholder="N" @click="selectedDom('periodicIncreaseInterval')" @input="
              form.periodicIncreaseInterval = limitInputNum(form.periodicIncreaseInterval, 3, 0, false)
              " /> 年递增
          <el-input :disabled="form.increaseMode != 2" style="width:70px;" v-model="form.increaseRate2"
            class="inputStyle" placeholder="%" @click="selectedDom('increaseRate2')"
            @input="form.increaseRate2 = limitInputNum(form.increaseRate2, 3, 0, true)" />%
        </el-radio>

        <el-radio :label="3">合同前
          <el-input :disabled="form.increaseMode != 3" style="width:70px;" v-model="form.discountMonths"
            class="inputStyle" placeholder="N" @click="selectedDom('discountMonths')" @input="
              form.discountMonths = limitInputNum(form.discountMonths, 3, 0, true)
              " />
          个月租金减免<el-input :disabled="form.increaseMode != 3" style="width:70px;" v-model="form.discountAmount1"
            class="inputStyle" placeholder="%" @click="selectedDom('discountAmount1')"
            @input="form.discountAmount1 = limitInputNum(form.discountAmount1, 3, 2, true)" />%,或租金减免<el-input
            :disabled="form.increaseMode != 3" style="width:170px;" v-model="form.discountAmount2" class="inputStyle"
            placeholder="N" @click="selectedDom('discountAmount2')" @input="
              form.discountAmount2 = limitInputNum(form.discountAmount2, 100, 2, true)
              " />元整
        </el-radio>
      </el-radio-group>
    </el-form-item>


    <el-form-item label="付款方式" prop="payType">
      <el-select v-model="form.payType" class="selectStyle" placeholder="请选择付款方式" @change="payTypeChange">
        <el-option v-for="item in payTypeOptionsArr" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="免租期" prop="freeRentMonth">
      <el-input v-model="form.freeRentMonth" class="inputStyle" placeholder="免租期（单位：月）"
        @input="form.freeRentMonth = limitInputNum(form.freeRentMonth, 4, 0, false)"
        @click="selectedDom('freeRentMonth')">
        <template #append>个月</template>
      </el-input>
    </el-form-item>
    <el-form-item label="增值税率" prop="taxRate">
      <el-input v-model="form.taxRate" class="inputStyle" maxlength="32" @click="selectedDom('taxRate')"
        placeholder="请输入增值税率" clearable @input="
          form.taxRate = limitInputNum(form.taxRate, 3, 0, true)">
        <template #append>%</template>
      </el-input>
    </el-form-item>

    <el-form-item label="实际物业费" prop="propertyFeeUnitPrice">
      <el-input v-model="form.propertyFeeUnitPrice" class="inputStyle" placeholder="请输入实际物业费金额（单位：元）"
        @input="form.propertyFeeUnitPrice = limitInputNum(form.propertyFeeUnitPrice, 9, 2, true)"
        @click="selectedDom('propertyFeeUnitPrice')" />
    </el-form-item>



    <el-form-item class="limitInput" label="签订时间" prop="signTime">
      <el-date-picker v-model="form.signTime" class="dateInputBox" value-format="YYYY-MM-DD" type="date"
        placeholder="请选择开业日期" size="large" @click="selectedDom('signTime')">
      </el-date-picker>
    </el-form-item>

    <el-form-item label="补充协议" prop="fileVoList">
      <FileMinioUpload :restriction="true" :restrictionLimit="9" v-model:files="form.fileVoList" />
    </el-form-item>
  </el-form>

  <SelectLeaseAssetDialog ref="LeaseAssetDialogRef" @getAssetId="getAssetId" />
  <SelectLeaseHouseDialog ref="LeaseHouseDialogRef" @getHouseInfo="getHouseInfo" />
  <SelectTenantryDialog ref="TenantryDialogRef" @getTenantryInfo="getTenantryInfo" />
</template>

<script setup>
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessage,
} from "element-plus";
import SelectLeaseAssetDialog from "@/views/assetManagement/companyContractManagement/templateManagement/components/selectLeaseAssetDialog";
import SelectLeaseHouseDialog from "@/views/assetManagement/companyContractManagement/templateManagement/components/selectLeaseHouseDialog";
import SelectTenantryDialog from "../components/SelectTenantryDialog";
import { useRouter } from "vue-router";
import { limitInputNum, localSet } from "@/common/utils/GlobalUtils";
import store from "@/store";
import {
  competeTypeOptionsArr,
  payTypeOptionsArr,
  signTypeOptionsArr,
} from "@/common/dict/dictCollect";
import { otherApi } from "@/api/assets";
import { onMounted, reactive, ref, watch, defineExpose } from "vue";
import dayjs from "dayjs";
import FileMinioUpload from "@/components/FileMinioUpload.vue";
const router = useRouter();
const emits = defineEmits(["selectedDom"]);
const selectedDom = (d) => {
  emits("selectedDom", d);
};
const contractTemplateId = router.currentRoute.value.params.contractTemplateId;


// form相关
const formRef = ref(null);
const form = reactive({
  assetsId: "1",
  assetsName: "1",
  address: "1",
  freeRentMonth: '0',
  signType: "", // 签约类型(1新签2续签)
  competitionLeaseType: "",//竞租方式
  customerName: '',//乙方名称
  leaseCustomers: [], // 乙方客户List
  haveAssetValFlag: "",//仅用于'资产'必填的提示
  haveCustomerValFlag: "", // 仅用于'承租方(乙方)'必填的提示
  haveHousingValFlag: "", // 仅用于'租赁的房源'必填的提示
  assetsList: [], // 资产list
  leaseHousings: [], // 房源list
  leaseTotalArea: "", //租赁总面积
  sign_time: [],
  signTime: '',//签订时间
  signStartTime: "", // 租赁开始时间
  signEndTime: "", // 租赁结束时间
  yearCount: "",//租聘期限多少年
  areaUnitPrice: "",//实际租金单价
  giveDay: "",//甲方交付驿站天数
  purpose: "",//使用目的
  businessPurpose: "",//经营用途
  openTime: "",//约定开业日期
  openDay: "",//根据约定开业日期和租聘开始日期计算相隔天数
  payType: "",//付款方式（1，月，2 季，3 半年,4 年）
  free_Time: [],//免租期
  // freeStartTime: "",//免租开始日期
  // freeEndTime: "",//免租结束日期
  taxRate: "",//增值税率
  deposit: "",//租聘保证金
  depositZN: "",//租聘保证金中文
  depositPayTime: "",//保证金缴纳时间
  propertyFeeUnitPrice: "",//实际物业费
  propertyCost: "",//物业费总计
  propertyCostZN: "",//物业费总计中文
  fileVoList: [], // 补充协议
  payeeId: "",



  increaseMode: 1,//递增模式
  periodicIncreaseInterval: "",//递增年份间
  increaseStartYear: "0",
  increaseStartYear1: "0",//增幅开始第几年
  increaseStartYear2: "",//增幅开始第几年
  discountMonths: "",//减免月数
  discountAmount: "",//减免金额
  discountAmount1: "",//减免金额
  discountAmount2: "",//减免金额
  increaseRate: "0",//增长幅度
  increaseRate1: "0",//增长幅度
  increaseRate2: "",//增长幅度
});

watch(() => { return form.increaseStartYear1 }, (value) => {
  form.increaseStartYear = value;
})
watch(() => { return form.increaseStartYear2 }, (value) => {

  form.increaseStartYear = value;
})
watch(() => { return form.increaseRate1 }, (value) => {

  form.increaseRate = value && (parseFloat(value) / 100).toFixed(2);
})
watch(() => { return form.increaseRate2 }, (value) => {

  form.increaseRate = value && (parseFloat(value) / 100).toFixed(2);
})


watch(() => { return form.discountAmount1 }, (value) => {
  console.log('discountAmount1', value);
  if (!value) {
    return
  }
  form.discountAmount = value && (parseFloat(value) / 100).toFixed(2);
  form.discountAmount1 = value//减免金额
  form.discountAmount2 = ""//减免金额
})
watch(() => { return form.discountAmount2 }, (value) => {
  console.log('discountAmount2', value);
  if (!value) {
    return
  }
  form.discountAmount = value;
  form.discountAmount2 = value;
  form.discountAmount1 = ""//减免金额
})


watch(() => { return form.deposit }, (value) => {
  var nzhhk = require("nzh/hk"); //繁体中文
  form.depositZN = nzhhk.encodeB(value);
})

const growChange = (value) => {

  form.increaseRate = ""
  form.increaseStartYear = "";
  form.increaseStartYear1 = ""//增幅开始第几年
  form.increaseRate1 = ""

  form.increaseStartYear2 = ""//增幅开始第几年
  form.periodicIncreaseInterval = ""//递增年份间隔
  form.increaseRate2 = ""

  form.discountMonths = ""//减免月数

  form.discountAmount = ""//减免金额
  form.discountAmount1 = ""//减免金额
  form.discountAmount2 = ""//减免金额

  switch (value) {
    case 1:
      form.increaseRate = "0"
      form.increaseRate1 = "0"
      form.increaseStartYear = "0";
      form.increaseStartYear1 = "0";
      break;
    case 2:
      form.increaseRate = "0"
      form.increaseRate2 = "0"
      form.increaseStartYear = "0";
      form.increaseStartYear2 = "0";
      form.periodicIncreaseInterval = "0";
      break;
    case 3:
      form.discountMonths = "0"
      form.discountAmount = "0"
      form.discountAmount1 = "0";
      form.discountAmount2 = "0";
      break;
    default:
      break;
  }
}
const formValidate = async () => {
  const valid = await formRef.value.validate().catch((err) => {
    //自定义catch方法，返回验证结果

    return err;
  });

  return { valid, form };
};

defineExpose({
  formValidate,
  form,
});
// 校验
const formRules = reactive({
  rules: {
    haveCustomerValFlag: [
      { required: true, trigger: "change", message: "请选择承租方(乙方)" },
    ],
    haveHousingValFlag: [
      { required: true, trigger: "change", message: "请选择租赁的房源" },
    ],
    competitionLeaseType: [
      { required: true, trigger: "change", message: "请选择竟租方式" },
    ],
    leaseAsset: [{ required: true, trigger: "change", message: "请选择租赁的资产" }],
    sign_time: [{ required: true, trigger: "change", message: "请选择租赁期限" }],
    freeRentMonth: [{ required: true, trigger: "blur", message: "请输入免租月数" }],
    businessPurpose: [{ required: true, trigger: "blur", message: "请输入经营用途" }],
    // purpose: [{ required: true, trigger: "blur", message: "请输入业态" }],
    areaUnitPrice: [{ required: true, trigger: "blur", message: "请输入租金单价" }],
    increaseStartYear: [{ required: true, trigger: "blur", message: "请输入年数" }],
    increaseRate: [{ required: true, trigger: "blur", message: "请输入递增比例" }],
    payType: [{ required: true, trigger: "change", message: "请选择付款方式" }],
    propertyCost: [{ required: true, trigger: "blur", message: "请输入物业管理费" }],
    signType: [{ required: true, trigger: "change", message: "请选择签约类型" }],
    deposit: [{ required: true, trigger: "blur", message: "请输入租赁保证金额" }],
    /*depositPayTime: [
      { required: true, trigger: "change", message: "请选择缴纳时间" },
    ],*/
    openTime: [{ required: true, trigger: "change", message: "请选择约定开始时间" }],
    term: [{ required: true, trigger: "blur", message: "请输入期限" }],
    startDescription: [{ required: true, trigger: "blur", message: "请输入起始说明" }],
    propertyDescription: [{ required: true, trigger: "blur", message: "请输入物业说明" }],
    explanationOfRentFreePeriod: [
      { required: true, trigger: "blur", message: "请输入免租期说明" },
    ],
    programme: [{ required: true, trigger: "blur", message: "请输入方案" }],
    integrityStatement: [{ required: true, trigger: "blur", message: "请输入廉洁说明" }],
    businessUnit: [{ required: true, trigger: "blur", message: "请输入业务单元" }],
    fileOne: [{ required: true, trigger: "change", message: "请上传营业执照" }],
    fileTwo: [{ required: true, trigger: "change", message: "请上传身份证" }],
    fileThree: [{ required: true, trigger: "change", message: "请上传租赁区域平面图" }],
    failureToObtainDocuments: [
      { required: true, trigger: "change", message: "请输入未办理证件" },
    ],
    documentsHaveBeenProcessed: [
      { required: true, trigger: "change", message: "请输入已办理证件" },
    ],
  },
});

// 收起/展开 相关
const rightBoxState = reactive({
  hideRightBoxFlag: false, // 控制右侧整体
  hideRightCnFlag: false, // 控制右侧内容部分
});
// 收起/展开按钮点击
const doControlRight = () => {
  rightBoxState.hideRightBoxFlag = !rightBoxState.hideRightBoxFlag;
  if (rightBoxState.hideRightBoxFlag) {
    // 收起时
    setTimeout(() => {
      // 延时控制，解决收起时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = true;
    }, 200);
  } else {
    // 展开时
    setTimeout(() => {
      // 延时控制，解决展开时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = false;
    }, 200);
  }
};

const competeTypeChange = (val) => {
  selectedDom("competitionLeaseType");
};

// 房源弹窗
const LeaseHouseDialogRef = ref(null);
const showHousingDialog = () => {
  const type = form.signType && form.signType.toString() || ""
  const ids = form.assetsList.map(r => r.assetsId)
  LeaseHouseDialogRef.value.open(ids, type);
};

// 资产弹窗
const LeaseAssetDialogRef = ref(null);
const showAssetDialog = () => {
  LeaseAssetDialogRef.value.open();
};

// 承租方
const TenantryDialogRef = ref(null);
const showTenantryDialog = (className) => {
  TenantryDialogRef.value.showTenantryDialog();
  selectedDom(className);
};

// 租赁方信息
const getTenantryInfo = (row) => {
  if (!row.customerId) {
    return ElMessage.error("脏数据!请联系管理员!");
  }
  let bool = false;
  form.leaseCustomers.forEach((item) => {
    if (item.customerId === row.customerId) {
      bool = true;
    }
  });
  if (bool) {
    ElMessage.warning(`不能选择相同客户!`);
    return;
  }
  form.leaseCustomers.push(row);
  form.haveCustomerValFlag = "已选择";
};
// 删除 租赁客户list
const doDeleteLeaseCustomersList = (index) => {
  form.leaseCustomers.splice(index, 1);
  if (form.leaseCustomers.length === 0) {
    form.haveCustomerValFlag = "";
  }
};

// 房源列表删除
const doDeletHousesList = (index) => {
  form.leaseHousings.splice(index, 1);
  if (form.leaseHousings.length === 0) {
    form.haveHousingValFlag = "";
  }
  getLeaseTotalArea();
};

// 约定开始时间要在保证金缴纳时间之后
const openDisabledDate = (time) => {
  if (form.depositPayTime) {
    return dayjs(time) < dayjs(form.depositPayTime);
  }
  return dayjs(time) < dayjs("2019-1-1");
};

/**
 * 付款方式
 */
const payTypeChange = () => {
  selectedDom("payType");
};

const signTypeChange = (val) => {
  selectedDom("signType");
};

const getAssetId = (val) => {
  let i = form.assetsList.findIndex((x) => x.assetsId === val.assetsId);
  if (i !== -1) {
    return ElMessage.warning("不能添加同一个资产!");
  }
  form.assetsList.push({ ...val });
  form.haveAssetValFlag = "已选择";

};

// 房源列表删除
const doDeletAssetsList = (index) => {
  form.assetsList.splice(index, 1);
  if (form.assetsList.length === 0) {
    form.haveAssetValFlag = "";
  }
};

const getHouseInfo = (val) => {
  let i = form.leaseHousings.findIndex((x) => x.housingId === val.housingId);
  if (i !== -1) {
    return ElMessage.warning("不能添加同一个房源!");
  }
  form.leaseHousings.push({
    housingId: val.housingId,
    leaseArea: val.area,
    areaUnitPrice: 0,
    housingNumber: val.housingNumber === null ? "" : val.housingNumber,
  });
  form.haveHousingValFlag = "已选择";
  getLeaseTotalArea();
};

//租赁开始/结束时间
const onSignTimeChange = (value) => {
  selectedDom("sign_Time");
  if (value && value !== "") {
    form.signStartTime = value[0];
    form.signEndTime = value[1];

    // 计算间隔月数
    const date1 = dayjs(value[0]);
    const date2 = dayjs(value[1]);
    const signMonthlyRent = date2.diff(date1, "month", true).toFixed(1);

    form.yearCount = (signMonthlyRent / 12).toFixed(2);

  }
};

//免租开始/结束时间
const onFreeTimeChange = (value) => {
  selectedDom("free_Time");
  if (value && value !== "") {
    form.freeStartTime = value[0];
    form.freeEndTime = value[1];

    // 计算间隔月数
    // const date1 = dayjs(value[0]);
    // const date2 = dayjs(value[1]);
    // const signMonthlyRent = date2.diff(date1, "month", true).toFixed(1);

    // form.yearCount = (form.term = (signMonthlyRent / 12).toFixed(2) + "年");
  }
};


/**
 * 租赁总面积
 */
const getLeaseTotalArea = () => {
  form.leaseTotalArea = 0;
  if (form.leaseHousings && form.leaseHousings.length !== 0) {
    form.leaseHousings.forEach((item) => {
      form.leaseTotalArea = form.leaseTotalArea + item.leaseArea;
    });
  }
};



/**
 * 监听form,用户在输入
 */
watch(
  form,
  (value) => {
    // 计算间隔月数
    const date1 = dayjs(value.openTime);
    const date2 = dayjs(value.signStartTime);
    form.openDay = date1.diff(date2, "day", true).toFixed(1);

    if (value.propertyFeeUnitPrice) {
      form.propertyCost = parseInt(form.propertyFeeUnitPrice) * form.leaseTotalArea
      var nzhhk = require("nzh/hk"); //繁体中文
      form.propertyCostZN = nzhhk.encodeB(form.propertyCost);
    }


    store.commit("SET_XIN_ZU_FORM_YIZHAN", form);
  },
  { deep: true }
);
const getCompanyBank = () => {
  otherApi.getCompanyBank().then((res) => {
    form.payeeId = res.data[0].payeeId;
  });
};

const initForm = () => {
  console.log(
    "store.state.collaborativeApproval.xinZuFormYiZhan",
    store.state.collaborativeApproval.xinZuFormYiZhan
  );
  if (
    store.state.collaborativeApproval.xinZuFormYiZhan &&
    JSON.stringify(store.state.collaborativeApproval.xinZuFormYiZhan) !== "{}"
  ) {
    for (let key in store.state.collaborativeApproval.xinZuFormYiZhan) {
      for (let key2 in form) {
        form[key] = store.state.collaborativeApproval.xinZuFormYiZhan[key];
      }
    }
  }
};

onMounted(() => {
  getCompanyBank();
  initForm();
});
</script>

<style lang="scss" scoped>
.form-container {
  :deep(.el-radio-group) {
    display: flex;
    flex-direction: column;

    .el-radio {
      height: auto;
      white-space: inherit;
    }

    .el-radio.is-checked {
      .el-radio__label {
        border: 1px solid var(--el-color-primary);
      }
    }
  }
}



:deep(.el-form) {
  .el-form-item {
    margin-bottom: 21px;

    .el-form-item__content {
      .selectStyle {
        width: 100%;
        // .select-trigger {
        //   .el-input__wrapper {
        //     box-shadow: 0 0 0 1px $input-focus-bd-color inset;
        //   }
        // }
      }

      .inputStyle {
        width: 100%;

        .el-input__wrapper {
          background-color: #fff8f6;

          //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
          .el-input__inner {
            text-align: center;
          }
        }
      }

      .inputCursor {
        .el-input__wrapper {
          .el-input__inner {
            cursor: pointer;
          }
        }
      }
    }
  }

  .limitInput {
    .el-form-item__content {
      display: flex;

      .dateRangeBox {
        margin-right: 6px;
        //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
      }

      .dateInputBox {
        flex: 1;

        .el-input__wrapper {
          width: 100%;
          //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
        }
      }

      .el-input {
        width: 100px;
      }
    }
  }
}

.housesListBox {
  .housesItemStyle {
    position: relative;

    .el-form-item__content {
      display: flex;

      .deletBtn {
        position: absolute;
        z-index: 1;
        left: -71px;
        cursor: pointer;
      }

      .el-input {
        flex: 1;

        &:nth-child(2) {
          margin-right: 10px;
        }
      }
    }
  }
}
</style>
